package com.shujia.mr.clazzSort;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class ClazzSortReducer extends Reducer<Text, Text, Text, Text> {

    /*
        1. 接受Map端发送过来的数据
        2. 对相同班级中的Values数据进行遍历
        3. 将学生数据报装成一个学生对象
        4. 将学生对象添加到List中
        5. 对List进行排序
        6. 取出前3名 写出
     */


    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, Text>.Context context) throws IOException, InterruptedException {
//        super.reduce(key, values, context);
        // values 表示相同班级中的所有学生数据  1500100001	施笑槐,22,女,文科六班,406

        ArrayList<Student> students = new ArrayList<>();

        for (Text value : values) {
            String oneStu = value.toString();
            String[] split = oneStu.split("\t");
            String id = split[0];
            String[] col = split[1].split(",");
            students.add(new Student(id, col[0], Integer.parseInt(col[1]), col[2], col[3], Integer.parseInt(col[4])));
        }


        /*
            , new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                // o1.score > o2.score ? 1 : o1.id.compareTo(o2.id) 表示正序排序
                return -(o1.score > o2.score ? 1 : o1.id.compareTo(o2.id));
            }
        }
         */

        // 排序
        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int res = o1.score - o2.score;
                return -(res == 0 ? o1.id.compareTo(o2.id) : res);
            }
        });

        // 写出数据 ArrayList中的下标就是排名
        for (int i = 0; i < 3; i++) {
            Student student = students.get(i);
            context.write(new Text(student.id), new Text(student.toString()));
        }


    }
}

class Student {
    String id;
    String name;
    int age;
    String gender;
    String clazz;
    int score;

    public Student(String id, String name, int age, String gender, String clazz, int score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.clazz = clazz;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", clazz='" + clazz + '\'' +
                ", score=" + score +
                '}';
    }




}
